package com.peng.ppscalelibrary.BleManager.Manager;

import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;


import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.beacon.BeaconItem;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.utils.BluetoothLog;
import com.inuker.bluetooth.library.utils.ByteUtils;
import com.peng.ppscalelibrary.BleManager.Interface.BleBMDJConnectInterface;
import com.peng.ppscalelibrary.BleManager.Interface.BleBMDJExitInterface;
import com.peng.ppscalelibrary.BleManager.Interface.BleBMDJInterface;
import com.peng.ppscalelibrary.BleManager.Interface.BleBMDJParttenInterface;
import com.peng.ppscalelibrary.BleManager.Interface.BleDataProtocoInterface;
import com.peng.ppscalelibrary.BleManager.Interface.BleDataStateInterface;
import com.peng.ppscalelibrary.BleManager.Interface.BleHeartRateInterface;
import com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel;
import com.peng.ppscalelibrary.BleManager.Model.BleDeviceModel;
import com.peng.ppscalelibrary.BleManager.Model.BleEnum;
import com.peng.ppscalelibrary.BleManager.Model.BleUserModel;
import com.peng.ppscalelibrary.BleManager.Model.LFPeopleGeneral;
import com.peng.ppscalelibrary.BleManager.util.BleUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.ADORE_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.BM_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.BODYFAT_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.BODYFAT_SCALE_1;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.CF367_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.ELECTRONIC_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.ENERGY_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.HEALTH_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.HEARTRATE_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.HUMAN_SCALE;
import static com.peng.ppscalelibrary.BleManager.Model.BleConnectFliterModel.WEIGHT_SCALE;

public class BleDataProtocoManager {

    double myWeightKg;

    int myImpedance;

    public BleDataProtocoManager(){
        super();
        myImpedance = 0;
        myWeightKg = 0;
    }


    /*连接后解析秤返回的数据*/
    public void analysisReciveData(String reciveData, String deviceMac, BleConnectFliterModel fliterModel, BleUserModel userModel, BleDataProtocoInterface protocoInterface, BleDataStateInterface stateInterface) {
        BluetoothLog.v("fliterModel getScaleName ------- " + fliterModel.getScaleName());

        if (fliterModel.getScaleName().equals(ELECTRONIC_SCALE) || fliterModel.getScaleName().equals(CF367_SCALE)) {

            electronicScaleProtocol(reciveData, fliterModel, deviceMac, userModel, protocoInterface, stateInterface);
        }

        if (fliterModel.getScaleName().equals(ADORE_SCALE) || fliterModel.getScaleName().equals(HEARTRATE_SCALE) || fliterModel.getScaleName().equals(WEIGHT_SCALE) || fliterModel.getScaleName().equals(BODYFAT_SCALE_1) ) {
            BluetoothLog.v("adoreScaleProtocol ------- " + fliterModel.getScaleName());

            adoreScaleProtocol(reciveData, fliterModel, deviceMac, userModel, protocoInterface, stateInterface);
        }
    }

    /*收到广播后解析数据*/
    public String analysisSearchData(SearchResult device, BleConnectFliterModel fliterModel) {

        Beacon beacon = new Beacon(device.scanRecord);
        for (BeaconItem beaconItem : beacon.mItems) {
            if (beaconItem.type == fliterModel.getAdvDataType()) {
                String data = ByteUtils.byteToString(beaconItem.bytes);
                BluetoothLog.v("unanalysisSearchfinalData ------- " + data);
                if (data.length() > 22) {
                        int startIndex = data.length() - 22;
                        String finalData = data.substring(startIndex, startIndex + 22);
                        BluetoothLog.v("analysisSearchfinalData ------- " + finalData);
                        if (finalData.startsWith("CF") || finalData.startsWith("CE")) {
                            BluetoothLog.v("analysisSearchfinalData ------- " + finalData);
                            return finalData;
                        }
                    }

            }
        }
        return "";
    }

    public boolean isLockedData(String reciveData) {
        String signLocked = reciveData.substring(18, 20);
        if (signLocked.equals("01")) {
            // 过程数据
            return false;

        } else {
            return true;
        }
    }

    /*向秤发送指令*/
    public List<byte[]> sendData(BleConnectFliterModel fliterModel, BleUserModel userModel) {
        if (fliterModel.getScaleName().equals(ENERGY_SCALE) ||
                fliterModel.getScaleName().equals(HEALTH_SCALE) ||
                fliterModel.getScaleName().equals(BM_SCALE) ||
                fliterModel.getScaleName().equals(BODYFAT_SCALE) ||
                fliterModel.getScaleName().equals(HUMAN_SCALE)
        ) {
            List<byte[]> resultArr = new ArrayList<>();
            resultArr.add(sendUnitData2Scale(userModel));
            return resultArr;
        } else if (fliterModel.getScaleName().equals(ELECTRONIC_SCALE) || fliterModel.getScaleName().equals(CF367_SCALE)) {

            return sendData2ElectronicScale(userModel);
        } else if ( fliterModel.getScaleName().equals(ADORE_SCALE) ||
                    fliterModel.getScaleName().equals(HEARTRATE_SCALE) ||
                    fliterModel.getScaleName().equals(WEIGHT_SCALE) ||
                    fliterModel.getScaleName().equals(BODYFAT_SCALE_1)
        ) {
            List<byte[]> resultArr = new ArrayList<>();
            resultArr.add(sendSyncHistoryData2AdoreScale());
            resultArr.add(sendUnitData2Scale(userModel));
            resultArr.add(sendSyncTimeData2AdoreScale());
            return resultArr;
        }
        return new ArrayList<>();
    }

    /*闭目单脚指令*/
    public byte[] sendMBDJData2Scale() {
        // 060F0000
        String byteStr = "06"
                + "0F"
                + "00"
                + "00";
        byte[] bytes = ByteUtils.stringToBytes(byteStr);
        return bytes;
    }

    /*退出闭目单脚指令*/
    public byte[] sendExitMBDJData2Scale() {
        // 060F0000
        String byteStr = "06"
                + "11"
                + "00"
                + "00";
        byte[] bytes = ByteUtils.stringToBytes(byteStr);
        return bytes;
    }


    public static byte[] deleteAdoreHistoryData() {
        String byteStr = "F201";
        byte[] bytes = ByteUtils.stringToBytes(byteStr);
        return bytes;
    }

    public static byte[] sendSyncHistoryData2AdoreScale() {

        String byteStr = "F200";
        byte[] bytes = ByteUtils.stringToBytes(byteStr);
        return bytes;
    }


    /*根据ElectronicScale协议解析*/
    private void electronicScaleProtocol(String reciveData,
                                         final BleConnectFliterModel fliterModel,
                                         final String deviceMac,
                                         BleUserModel userModel,
                                         final BleDataProtocoInterface protocoInterface,
                                         final BleDataStateInterface stateInterface) {

        BluetoothLog.v("electronicScaleProtocol ------- " + reciveData );


        if (reciveData.length() != 32) {
            return;
        }
        // 1  2  3  4  5  6     7    8    9    10   11  12    13   14   15   16
        // 01 23 45 67 89 1011 1213 1415 1617 1819 2021 2223 2425 2627 2829 3031
        // CF 03 99 AA 01 1C   00   32   0A   01   00   01   03   52   05   C5

        String preStr = reciveData.substring(0, 2);
        if (preStr.equals(BleEnum.BLE_SCALE_TYPE_CF) ) {

            String weightDataLow = reciveData.substring(8, 10);
            String weightDataHigh = reciveData.substring(10, 12);
            final double weightKg = (double) hexToTen(weightDataLow + weightDataHigh) / 10.0;

            double bmi = weightKg / Math.pow(((double) userModel.userHeight / 100.0), 2);

            String fatDataLow = reciveData.substring(12, 14);
            String fatDataHigh = reciveData.substring(14, 16);
            double bodyfatPercentage = (double) hexToTen(fatDataLow + fatDataHigh) / 10.0;

            String boneData = reciveData.substring(16, 18);
            double boneKg = (double) hexToTen(boneData) / 10.0;

            String muscleDataLow = reciveData.substring(18, 20);
            String muscleDataHigh = reciveData.substring(20, 22);
            double muscleKg = (double) hexToTen(muscleDataLow + muscleDataHigh) / 10.0;

            String VFLData = reciveData.substring(22, 24);
            int VFL = hexToTen(VFLData);

            String waterPercentageDataLow = reciveData.substring(24, 26);
            String waterPercentageDataHigh = reciveData.substring(26, 28);
            double waterPercentage = (double) hexToTen(waterPercentageDataLow + waterPercentageDataHigh) / 10.0;


            String BMRDataLow = reciveData.substring(28, 30);
            String BMRDataHigh = reciveData.substring(30, 32);
            int BMR = hexToTen(BMRDataLow + BMRDataHigh);

            int sex = sexEnum2Int(userModel.sex);
            final LFPeopleGeneral bodyDataModel = new LFPeopleGeneral(weightKg, userModel.userHeight, sex, userModel.age, 0, 0, 0, BleEnum.BLE_SCALE_TYPE_CF, fliterModel.getScaleName());
            bodyDataModel.lfWeightKg = weightKg;
            bodyDataModel.lfBMI = bmi;
            bodyDataModel.lfBodyfatPercentage = bodyfatPercentage;
            bodyDataModel.lfBoneKg = boneKg;
            bodyDataModel.lfMuscleKg = muscleKg;
            bodyDataModel.lfVFAL = VFL;
            bodyDataModel.lfWaterPercentage = waterPercentage;
            bodyDataModel.lfBMR = BMR;

            final BleDeviceModel deviceModel = new BleDeviceModel(deviceMac, fliterModel.getScaleName());
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    protocoInterface.lockedData(bodyDataModel, deviceModel, false);
                    // 设备信息
                    protocoInterface.deviceInfo(deviceModel);
                }
            });

        }
    }


    /*根据HeartRateScale协议解析*/
    public void heartRateScaleProtocol(
            String reciveData,
            final BleConnectFliterModel fliterModel,
            final String deviceMac,
            final BleUserModel userModel,
            final BleDataProtocoInterface protocoInterface,
            final BleHeartRateInterface heartRateInterface) {

        if (reciveData.length() >= 22) {
            reciveData = reciveData.substring(0, 22);
        } else {
            return;
        }

        String preStr = reciveData.substring(0, 2);
        if (preStr.equals(BleEnum.BLE_SCALE_TYPE_CF)) {

            String weightDataHigh = reciveData.substring(6, 8);
            String weightDataLow = reciveData.substring(8, 10);
            final double weightKg = (double) hexToTen(weightDataLow + weightDataHigh) / 100.0;

            final int sex = sexEnum2Int(userModel.sex);

            int impedance = 0;
            String impedanceHigh = reciveData.substring(10, 12);
            String impedanceMid = reciveData.substring(12, 14);
            String impedanceLow = reciveData.substring(14, 16);
            impedance = hexToTen(impedanceLow + impedanceMid + impedanceHigh);



            final String signLocked = reciveData.substring(18, 20);
            Handler handler = new Handler(Looper.getMainLooper());
            final int finalImpedance = impedance;
            final String finalReciveData = reciveData;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (signLocked.equals("01")) {
                        final LFPeopleGeneral bodyDataModel = new LFPeopleGeneral(weightKg, userModel.userHeight, sex, userModel.age, finalImpedance, 0, 0, BleEnum.BLE_SCALE_TYPE_CF, fliterModel.getScaleName());
                        // 过程数据
                        BluetoothLog.v("progress weight ------- " + weightKg);
                        protocoInterface.progressData(bodyDataModel);

                    } else {
                        if (weightKg > 0){
                            myWeightKg = weightKg;
                        }
                        if (finalImpedance > 0){
                            myImpedance = finalImpedance;
                        }
                        final LFPeopleGeneral bodyDataModel = new LFPeopleGeneral(myWeightKg, userModel.userHeight, sex, userModel.age, myImpedance, 0, 0, BleEnum.BLE_SCALE_TYPE_CF, fliterModel.getScaleName());

                        // 锁定数据
                        BleDeviceModel deviceModel = new BleDeviceModel(deviceMac, fliterModel.getScaleName());
                        final String heartRateSign = finalReciveData.substring(4, 6);

                        String s = Integer.toBinaryString(hexToTen(heartRateSign));
                        BluetoothLog.v("locked weight ------- " + myWeightKg + "impedanceInt ------- " + myImpedance + "heartRateSign ------- " + s);

                        if (s.startsWith("10")){
                            bodyDataModel.setLfHeartRate(0);
                            protocoInterface.lockedData(bodyDataModel, deviceModel, true);
                            heartRateInterface.heartRatingState(false);
                        }else if (s.startsWith("11")){
                            if (myWeightKg > 0){
                                String heartRateStr = finalReciveData.substring(2, 4);
                                int heartRate = hexToTen(heartRateStr);
                                bodyDataModel.setLfHeartRate(heartRate);
                                BluetoothLog.v("heartRateStr ------- " + heartRate );

                                protocoInterface.lockedData(bodyDataModel, deviceModel, false);
                                heartRateInterface.heartRatingState(true);
                                myImpedance = 0;
                            }
                            myWeightKg = 0;
                        }else if (s.startsWith("0")){
                            bodyDataModel.setLfHeartRate(0);
                            if (myWeightKg > 0){
                                protocoInterface.lockedData(bodyDataModel, deviceModel, false);
                                heartRateInterface.heartRatingState(true);
                                myImpedance = 0;
                            }
                            myWeightKg = 0;
                        }
                        // 设备信息
                        protocoInterface.deviceInfo(deviceModel);
                    }
                }
            });
        }
    }


    /*根据EnergyScale协议解析*/
    public void energyScaleProtocol(
            String reciveData,
            final BleConnectFliterModel fliterModel,
            final String deviceMac,
            BleUserModel userModel,
            final BleDataProtocoInterface protocoInterface) {

        if (reciveData.length() >= 22) {
            reciveData = reciveData.substring(0, 22);
        } else {
            return;
        }

        String preStr = reciveData.substring(0, 2);
        if (preStr.equals(BleEnum.BLE_SCALE_TYPE_CF)) {

            String weightDataHigh = reciveData.substring(6, 8);
            String weightDataLow = reciveData.substring(8, 10);
            final double weightKg = (double) hexToTen(weightDataLow + weightDataHigh) / 100.0;

            int sex = sexEnum2Int(userModel.sex);

            int impedance = 0;
            String impedanceHigh = reciveData.substring(10, 12);
            String impedanceMid = reciveData.substring(12, 14);
            String impedanceLow = reciveData.substring(14, 16);
            impedance = hexToTen(impedanceLow + impedanceMid + impedanceHigh);


            final LFPeopleGeneral bodyDataModel = new LFPeopleGeneral(weightKg, userModel.userHeight, sex, userModel.age, impedance, 0, 0, BleEnum.BLE_SCALE_TYPE_CF, fliterModel.getScaleName());

            final String signLocked = reciveData.substring(18, 20);
            Handler handler = new Handler(Looper.getMainLooper());
            final int finalImpedance = impedance;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (signLocked.equals("01")) {

                        // 过程数据
                        BluetoothLog.v("progress weight ------- " + weightKg);
                        if (bodyDataModel != null){
                            protocoInterface.progressData(bodyDataModel);
                        }

                    } else {

                        // 锁定数据
                        BluetoothLog.v("locked weight ------- " + weightKg + "impedanceInt ------- " + finalImpedance);
                        BleDeviceModel deviceModel = new BleDeviceModel(deviceMac, fliterModel.getScaleName());
                        if (bodyDataModel != null && deviceModel != null){
                            protocoInterface.lockedData(bodyDataModel, deviceModel, false);
                            // 设备信息
                            protocoInterface.deviceInfo(deviceModel);
                        }

                    }
                }
            });


        } else if (preStr.equals(BleEnum.BLE_SCALE_TYPE_CE)) {
            String weightDataHigh = reciveData.substring(6, 8);
            String weightDataLow = reciveData.substring(8, 10);
            final double weightKg = (double) hexToTen(weightDataLow + weightDataHigh) / 100.0;
            final String signLocked = reciveData.substring(18, 20);

            int sex = sexEnum2Int(userModel.sex);
            final LFPeopleGeneral bodyDataModel = new LFPeopleGeneral(weightKg, userModel.userHeight, sex, userModel.age, 0, 0, 0, BleEnum.BLE_SCALE_TYPE_CF, fliterModel.getScaleName());
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (signLocked.equals("01")) {

                        // 过程数据
                        BluetoothLog.v("progress weight ------- " + weightKg);
                        if (bodyDataModel != null){
                            protocoInterface.progressData(bodyDataModel);
                        }

                    } else {

                        // 锁定数据
                        BluetoothLog.v("locked weight ------- " + weightKg);
                        BleDeviceModel deviceModel = new BleDeviceModel(deviceMac, fliterModel.getScaleName());
                        if (bodyDataModel != null && deviceModel != null){
                            protocoInterface.lockedData(bodyDataModel, deviceModel, false);
                            // 设备信息
                            protocoInterface.deviceInfo(deviceModel);
                        }
                    }
                }
            });
        }
    }

    /*根据VFitTARTI协议解析  F0E7 00000064 已过滤掉前面的mac和时间戳*/
    public void vFitTARTIProtocol(
            String reciveData,
            final BleConnectFliterModel fliterModel,
            final String deviceMac,
            BleUserModel userModel,
            final BleDataProtocoInterface protocoInterface) {

        if (reciveData.length() >= 12) {
            reciveData = reciveData.substring(0, 12);
        } else {
            return;
        }
        if (reciveData.startsWith(BleEnum.BLE_SCALE_TYPE_F)) {

            String weightHex = reciveData.substring(1, 4);
            final double weightKg = (double) hexToTen(weightHex) / 10.0;
            int sex = sexEnum2Int(userModel.sex);
            int impedance = 0;
            String impedanceHigh = reciveData.substring(4, 6);
            String impedanceMid = reciveData.substring(6, 8);
            String impedanceLow = reciveData.substring(8, 10);
            impedance = hexToTen(impedanceLow + impedanceMid + impedanceHigh);

            final LFPeopleGeneral bodyDataModel = new LFPeopleGeneral(weightKg, userModel.userHeight, sex, userModel.age, impedance, 0, 0, BleEnum.BLE_SCALE_TYPE_F, fliterModel.getScaleName());

            Handler handler = new Handler(Looper.getMainLooper());
            final int finalImpedance = impedance;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    // 锁定数据
                    BluetoothLog.v("locked weight ------- " + weightKg + "impedanceInt ------- " + finalImpedance);
                    BleDeviceModel deviceModel = new BleDeviceModel(deviceMac, fliterModel.getScaleName());
                    protocoInterface.lockedData(bodyDataModel, deviceModel, false);
                    // 设备信息
                    protocoInterface.deviceInfo(deviceModel);
                }
            });
        } else if (reciveData.startsWith(BleEnum.BLE_SCALE_TYPE_E)) {
            String weightHex = reciveData.substring(1, 4);
            final double weightKg = (double) hexToTen(weightHex) / 10.0;
            int sex = sexEnum2Int(userModel.sex);
            final LFPeopleGeneral bodyDataModel = new LFPeopleGeneral(weightKg, userModel.userHeight, sex, userModel.age, 0, 0, 0, BleEnum.BLE_SCALE_TYPE_F, fliterModel.getScaleName());
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    // 锁定数据
                    BluetoothLog.v("locked weight ------- " + weightKg);
                    BleDeviceModel deviceModel = new BleDeviceModel(deviceMac, fliterModel.getScaleName());
                    protocoInterface.lockedData(bodyDataModel, deviceModel, false);
                    // 设备信息
                    protocoInterface.deviceInfo(deviceModel);
                }
            });
        }
    }

    /*BM Scale秤的时间数据*/
    public void bmScaleProtocol(String reciveData, BleConnectFliterModel fliterModel, BleBMDJInterface bmdjInterface) {
        BluetoothLog.v(reciveData);

        int time = 0;
        boolean isEnd = false;
        if (reciveData.startsWith("10060F01")) {
            isEnd = false;
        }

        if (reciveData.startsWith("10060F02")) {
            isEnd = true;
        }
        String timeHigh = reciveData.substring(8, 10);
        String timeLow = reciveData.substring(10, 12);
        time = hexToTen(timeLow + timeHigh);

        if (bmdjInterface != null) {
            bmdjInterface.timeInterval(time, isEnd);
        }

    }

    /*是否进入了闭目单脚模式*/
    public void bmScaleStatusProtocol(String reciveData, BleConnectFliterModel fliterModel, BleBMDJConnectInterface connectInterface) {
        if (reciveData.equals("10060F0001") && connectInterface != null) {
            connectInterface.connectSuccess();
        }
        if (reciveData.equals("10060F0003") && connectInterface != null) {
            connectInterface.connectFailed();
        }
    }

    /*是否退出了闭目单脚模式*/
    public void bmScaleExitStatusProtocol(String reciveData, BleConnectFliterModel fliterModel, BleBMDJExitInterface exitInterface) {
        if (reciveData.equals("1006110001") && exitInterface != null) {
            exitInterface.exitSuccess();
        }
        if (reciveData.equals("1006110003") && exitInterface != null) {
            exitInterface.exitFailed();
        }
    }


    /*BM Scale秤开始计时*/
    public void bmScaleStartTimingProtocol(String reciveData, BleConnectFliterModel fliterModel, BleBMDJParttenInterface parttenInterface) {
        BluetoothLog.v(reciveData);
        if (reciveData.equals("10060F010100") && parttenInterface != null) {
            parttenInterface.startTiming();
        }
    }


    /*根据adore秤解析数据*/
    private void adoreScaleProtocol(
            String reciveData,
            BleConnectFliterModel fliterModel,
            String deviceMac,
            BleUserModel userModel,
            final BleDataProtocoInterface protocoInterface,
            final BleDataStateInterface stateInterface) {

        // CF 4E 11 00 14 00 00 00 00 22 A6  C9 07 E1 08 11 15 04 30
        // CF 00 00 DC 05 00 00 00 00 00 16 07 E2 09 0E 0E 3A 28
        if (reciveData.length() == fliterModel.getHistoryDataLength()) {

            String preStr = reciveData.substring(0, 2);
            if (preStr.equals(BleEnum.BLE_SCALE_TYPE_CF)||
                    preStr.equals(BleEnum.BLE_SCALE_TYPE_CE)) {

                String weightDataHigh = reciveData.substring(6, 8);
                String weightDataLow = reciveData.substring(8, 10);
                double weightKg = (double) hexToTen(weightDataLow + weightDataHigh) / 100.0;

                int sex = sexEnum2Int(userModel.sex);

                int impedance = 0;
                String impedanceHigh = reciveData.substring(10, 12);
                String impedanceMid = reciveData.substring(12, 14);
                String impedanceLow = reciveData.substring(14, 16);
                impedance = hexToTen(impedanceLow + impedanceMid + impedanceHigh);


                final LFPeopleGeneral bodyDataModel = new LFPeopleGeneral(weightKg, userModel.userHeight, sex, userModel.age, impedance, 0, 0, preStr, fliterModel.getScaleName());
                String heartSign = reciveData.substring(4, 6);

                if (heartSign.startsWith("C0")){
                    int heartRate = hexToTen(reciveData.substring(2, 4));
                    bodyDataModel.setLfHeartRate(heartRate);
                }else{
                    bodyDataModel.setLfHeartRate(0);
                }

                int year = hexToTen(reciveData.substring(22, 24) + reciveData.substring(24, 26));
                int mounth = hexToTen(reciveData.substring(26, 28));
                int day = hexToTen(reciveData.substring(28, 30));
                int hour = hexToTen(reciveData.substring(30, 32));
                int minite = hexToTen(reciveData.substring(32, 34));
                int secound = hexToTen(reciveData.substring(34, 36));


                // 设备信息
                final BleDeviceModel deviceModel = new BleDeviceModel(deviceMac, fliterModel.getScaleName());
                String clock = year + "-";
                if (mounth < 10) clock += "0";
                clock += mounth + "-";
                if (day < 10) clock += "0";
                clock += day + " ";
                if (hour < 10) clock += "0";
                clock += hour + ":";
                if (minite < 10) clock += '0';
                clock += minite + ":";
                if (secound < 10) clock += '0';
                clock += secound;

                Handler handler = new Handler(Looper.getMainLooper());
                final String finalClock = clock;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        protocoInterface.deviceInfo(deviceModel);
                        protocoInterface.historyData(false, bodyDataModel, finalClock);
                    }
                });
//                BluetoothLog.v("bodyDataModel.toString() ------- " + bodyDataModel.toString());


            }


        } else if (reciveData.length() == fliterModel.getHistoryEndDataLength()) {
            if (reciveData.equals("F200")) {
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        stateInterface.sendHistoryData();
                        protocoInterface.historyData(true, null, "");
                    }
                });
            }
        }
    }

    /*根据VFitTARTI协议解析  F0E7 00000064 已过滤掉前面的mac和时间戳*/
    private void vFitTARTIProtocol(
            String reciveData,
            BleConnectFliterModel fliterModel,
            String deviceMac,
            BleUserModel userModel,
            final BleDataProtocoInterface protocoInterface,
            final BleDataStateInterface stateInterface) {

        // 17 07 17 34 1B F0 6B 00 00 00
        if (reciveData.length() == fliterModel.getHistoryDataLength()) {

            String preStr = reciveData.substring(10, 11);

            if (preStr.equals(BleEnum.BLE_SCALE_TYPE_F)) {

                String weightHex = reciveData.substring(11, 14);
                final double weightKg = (double) hexToTen(weightHex) / 10.0;
                int sex = sexEnum2Int(userModel.sex);

                int impedance = 0;
                String impedanceHigh = reciveData.substring(14, 16);
                String impedanceMid = reciveData.substring(16, 18);
                String impedanceLow = reciveData.substring(18, 20);
                impedance = hexToTen(impedanceLow + impedanceMid + impedanceHigh);

                final LFPeopleGeneral bodyDataModel = new LFPeopleGeneral(weightKg, userModel.userHeight, sex, userModel.age, impedance, 0, 0, BleEnum.BLE_SCALE_TYPE_CF, fliterModel.getScaleName());

                int year = hexToTen(reciveData.substring(0, 1))+ 2017;
                int mounth = hexToTen(reciveData.substring(1, 2));
                int day = hexToTen(reciveData.substring(2, 4));
                int hour = hexToTen(reciveData.substring(4,6));
                int minite = hexToTen(reciveData.substring(6, 8));
                int secound = hexToTen(reciveData.substring(8, 10));

                // 设备信息
                final BleDeviceModel deviceModel = new BleDeviceModel(deviceMac, fliterModel.getScaleName());
                String clock = year + "-";
                if (mounth < 10) clock += "0";
                clock += mounth + "-";
                if (day < 10) clock += "0";
                clock += day + " ";
                if (hour < 10) clock += "0";
                clock += hour + ":";
                if (minite < 10) clock += '0';
                clock += minite + ":";
                if (secound < 10) clock += '0';
                clock += secound;

                Handler handler = new Handler(Looper.getMainLooper());
                final String finalClock = clock;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        protocoInterface.deviceInfo(deviceModel);
                        protocoInterface.historyData(false, bodyDataModel, finalClock);
                    }
                });
            }

        } else if (reciveData.length() == fliterModel.getHistoryEndDataLength()) {
            if (reciveData.equals("F200")) {
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        stateInterface.sendHistoryData();
                        protocoInterface.historyData(true, null, "");
                    }
                });
            }
        }
    }


    private static List<byte[]> sendData2ElectronicScale(BleUserModel userModel) {
        int sex = sexEnum2Int(userModel.sex);
        int unit = electronicUnitEnum2Int(userModel.unit);

        String byteStr = "FE"
                + decimal2Hex(userModel.groupNum)
                + decimal2Hex(sex)
                + decimal2Hex(0)
                + decimal2Hex(userModel.userHeight)
                + decimal2Hex(userModel.age)
                + decimal2Hex(unit);
        byte[] bytes = ByteUtils.stringToBytes(byteStr);
        byte[] xorByte = getXorForElectronicScale(bytes);
        List<byte[]> resultArr = new ArrayList<>();
        resultArr.add(xorByte);
        return resultArr;
    }

    private static byte[] sendUnitData2Scale(BleUserModel userModel) {
        int sex = sexEnum2Int(userModel.sex);
        int unit = energyUnitEnum2Int(userModel.unit);
        String byteStr = "FD"
                + "00"
                + decimal2Hex(unit)
                + "00"
                + "00"
                + "00"
                + "00"
                + "00"
                + "00"
                + "00";
        byte[] bytes = ByteUtils.stringToBytes(byteStr);
        byte[] xorByte = getXor(bytes);
        return xorByte;
    }

    private static byte[] sendSyncTimeData2AdoreScale() {

        // 获取指定格式的时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd/HH/mm/ss");
        // 输出字符串
        String dateStr = df.format(new Date());
        String[] strArr = dateStr.split("/");
        String byteStr = "F1";
        for (String s : strArr) {
            int target = Integer.parseInt(s);
            byteStr += decimal2Hex(target);
        }
        byte[] bytes = ByteUtils.stringToBytes(byteStr);
        return bytes;
    }

    /*16进制字符串转10进制int*/
    private static int hexToTen(String hex) {
        if (TextUtils.isEmpty(hex)) {
            return 0;
        }
        return Integer.valueOf(hex, 16);
    }

    /*ElectronicScale异或检验*/
    private static byte[] getXorForElectronicScale(byte[] datas) {

        byte[] bytes = new byte[datas.length + 1];
        byte temp = datas[1];
        bytes[0] = datas[0];
        bytes[1] = datas[1];
        for (int i = 2; i < datas.length; i++) {
            bytes[i] = datas[i];
            temp ^= datas[i];
        }
        bytes[datas.length] = temp;
        return bytes;
    }

    /*异或检验*/
    private static byte[] getXor(byte[] datas) {

        byte[] bytes = new byte[datas.length + 1];
        byte temp = datas[0];
        bytes[0] = datas[0];
        for (int i = 1; i < datas.length; i++) {
            bytes[i] = datas[i];
            temp ^= datas[i];
        }
        bytes[datas.length] = temp;
        return bytes;
    }


    /*性别*/
    private static int sexEnum2Int(BleEnum.BleSex enumSex) {
        int sex = 0;
        switch (enumSex) {
            case Male:
                sex = 1;
                break;
            case Female:
                sex = 0;
                break;
        }
        return sex;
    }

    /*ElectronicScale单位*/
    private static int electronicUnitEnum2Int(BleEnum.BleUnit enumUnit) {
        int unit = 0;
        switch (enumUnit) {
            case BLE_UNIT_KG:
                unit = 1;
                break;
            case BLE_UNIT_LB:
                unit = 2;
                break;
            case BLE_UNIT_JIN:
                unit = 1;
                break;
            case BLE_UNIT_ST_LB:
                unit = 4;
                break;
        }
        return unit;
    }

    private static int energyUnitEnum2Int(BleEnum.BleUnit enumUnit) {
        int unit = 0;
        switch (enumUnit) {
            case BLE_UNIT_KG:
                unit = 0;
                break;
            case BLE_UNIT_LB:
                unit = 1;
                break;
            case BLE_UNIT_JIN:
                unit = 3;
                break;
            case BLE_UNIT_ST_LB:
                unit = 0;
                break;
        }
        return unit;
    }

    private static String decimal2Hex(int decimal) {
        String hex = "";
        String letter;
        int number;
        for (int i = 0; i < 9; i++) {

            number = decimal % 16;
            decimal = decimal / 16;
            switch (number) {

                case 10:
                    letter = "A";
                    break;
                case 11:
                    letter = "B";
                    break;
                case 12:
                    letter = "C";
                    break;
                case 13:
                    letter = "D";
                    break;
                case 14:
                    letter = "E";
                    break;
                case 15:
                    letter = "F";
                    break;
                default:
                    letter = String.valueOf(number);
            }
            hex = letter + hex;
            if (decimal == 0) {
                break;
            }
        }
        if (hex.length() % 2 != 0) {
            hex = "0" + hex;
        }
        return hex;
    }

}
